<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>自制深度学习框架--算子的执行流程 | kiloGrand</title><meta name="keywords" content="kuiper_infer"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="计算图执行的图示计算节点的执行是通过广度优先搜索来实现的，如下图所示。详细请看：https:&#x2F;&#x2F;zhuanlan.zhihu.com&#x2F;p&#x2F;607993700 寻找并拷贝上一级的输出到后继节点的输入123456789101112131415161718192021222324252627282930313233void RuntimeGraph::ProbeNextLayer(    const s">
<meta property="og:type" content="article">
<meta property="og:title" content="自制深度学习框架--算子的执行流程">
<meta property="og:url" content="https://kilogrand.gitee.io/2023/03/22/kuiper_infer-L12/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="计算图执行的图示计算节点的执行是通过广度优先搜索来实现的，如下图所示。详细请看：https:&#x2F;&#x2F;zhuanlan.zhihu.com&#x2F;p&#x2F;607993700 寻找并拷贝上一级的输出到后继节点的输入123456789101112131415161718192021222324252627282930313233void RuntimeGraph::ProbeNextLayer(    const s">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2023-03-22T12:00:00.000Z">
<meta property="article:modified_time" content="2023-04-21T14:46:51.813Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="kuiper_infer">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2023/03/22/kuiper_infer-L12/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '自制深度学习框架--算子的执行流程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-21 22:46:51'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">自制深度学习框架--算子的执行流程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-21T14:46:51.813Z" title="更新于 2023-04-21 22:46:51">2023-04-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">深度学习</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>5分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="自制深度学习框架--算子的执行流程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="计算图执行的图示"><a href="#计算图执行的图示" class="headerlink" title="计算图执行的图示"></a>计算图执行的图示</h2><p>计算节点的执行是通过广度优先搜索来实现的，如下图所示。<br><img src="https://pic2.zhimg.com/80/v2-ccbed9e942157665aa8e631ab46e007d_1440w.webp" alt=""><br>详细请看：<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/607993700">https://zhuanlan.zhihu.com/p/607993700</a></p>
<h2 id="寻找并拷贝上一级的输出到后继节点的输入"><a href="#寻找并拷贝上一级的输出到后继节点的输入" class="headerlink" title="寻找并拷贝上一级的输出到后继节点的输入"></a>寻找并拷贝上一级的输出到后继节点的输入</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">RuntimeGraph::ProbeNextLayer</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> std::shared_ptr&lt;RuntimeOperator&gt; &amp;current_op,</span></span></span><br><span class="line"><span class="params"><span class="function">    std::deque&lt;std::shared_ptr&lt;RuntimeOperator&gt;&gt; &amp;operator_queue,</span></span></span><br><span class="line"><span class="params"><span class="function">    std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; layer_output_datas)</span> </span>&#123;</span><br><span class="line">  <span class="comment">// current_op表示当前执行完毕的节点，operator_queue就是在节点执行队列，</span></span><br><span class="line">  <span class="comment">// layer_output_datas就是当前current_op被执行后得到的对应输出</span></span><br><span class="line">  <span class="type">const</span> <span class="keyword">auto</span> &amp;next_ops = current_op-&gt;output_operators;</span><br><span class="line"></span><br><span class="line">  std::vector&lt;std::vector&lt;std::shared_ptr&lt;ftensor&gt;&gt;&gt; next_input_datas_arr;</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;next_op : next_ops) &#123;</span><br><span class="line">    <span class="comment">// 遍历当前节点的output_operators</span></span><br><span class="line">    <span class="type">const</span> <span class="keyword">auto</span> &amp;next_rt_operator = next_op.second;  <span class="comment">// 获取键值对中value</span></span><br><span class="line">    <span class="type">const</span> <span class="keyword">auto</span> &amp;next_input_operands = next_rt_operator-&gt;input_operands;  <span class="comment">// 获取next_op的输入操作数</span></span><br><span class="line">    <span class="comment">// 找到后继节点</span></span><br><span class="line">    <span class="keyword">if</span> (next_input_operands.<span class="built_in">find</span>(current_op-&gt;name) !=</span><br><span class="line">        next_input_operands.<span class="built_in">end</span>()) &#123;</span><br><span class="line">      <span class="comment">// 把下一节点的输入数据的指针添加到next_input_datas_arr中</span></span><br><span class="line">      std::vector&lt;std::shared_ptr&lt;ftensor&gt;&gt; next_input_datas =</span><br><span class="line">          next_input_operands.<span class="built_in">at</span>(current_op-&gt;name)-&gt;datas;</span><br><span class="line">      next_input_datas_arr.<span class="built_in">push_back</span>(next_input_datas);</span><br><span class="line">      next_rt_operator-&gt;meet_num += <span class="number">1</span>;</span><br><span class="line">      <span class="keyword">if</span> (std::<span class="built_in">find</span>(operator_queue.<span class="built_in">begin</span>(), operator_queue.<span class="built_in">end</span>(),</span><br><span class="line">                    next_rt_operator) == operator_queue.<span class="built_in">end</span>()) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">CheckOperatorReady</span>(next_rt_operator)) &#123;</span><br><span class="line">          <span class="comment">// 如果meet_num的数量等于它前驱的数量，说明它现在可以被放入到执行队列中。</span></span><br><span class="line">          operator_queue.<span class="built_in">push_back</span>(next_rt_operator);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 将layer_output_datas这个输出张量复制到next_input_datas_arr这个张量数组（后继的输入）上</span></span><br><span class="line">  <span class="built_in">SetOpInputData</span>(layer_output_datas, next_input_datas_arr);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">bool</span> <span class="title">RuntimeGraph::CheckOperatorReady</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> std::shared_ptr&lt;RuntimeOperator&gt; &amp;op)</span> </span>&#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(op != <span class="literal">nullptr</span>);</span><br><span class="line">  <span class="built_in">CHECK</span>(op-&gt;meet_num &lt;= op-&gt;input_operands.<span class="built_in">size</span>());</span><br><span class="line">  <span class="comment">// 如果meet_num的数量等于它前驱的数量，也就是输入操作数的个数</span></span><br><span class="line">  <span class="keyword">if</span> (op-&gt;meet_num == op-&gt;input_operands.<span class="built_in">size</span>()) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="广度优先搜索的执行顺序的实现"><a href="#广度优先搜索的执行顺序的实现" class="headerlink" title="广度优先搜索的执行顺序的实现"></a>广度优先搜索的执行顺序的实现</h2><p>广度优先搜索执行的实现是使用一个队列，将一个节点的入度为0的后继节点放入到队列中，<br>并在下一轮循环中按照先进先出的顺序对队列中的节点进行执行。</p>
<p><img src="https://pic2.zhimg.com/80/v2-ccbed9e942157665aa8e631ab46e007d_1440w.webp" alt=""></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br></pre></td><td class="code"><pre><span class="line">std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt;</span><br><span class="line">RuntimeGraph::<span class="built_in">Forward</span>(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; &amp;inputs,</span><br><span class="line">                      <span class="type">bool</span> debug) &#123;</span><br><span class="line">  <span class="comment">// 对图状态的检查，只有图状态为complete的时候才能执行图的调度</span></span><br><span class="line">  <span class="comment">// 即图中的计算节点都初始化完毕，输入输入输出算子都准备好相关的空间之后</span></span><br><span class="line">  <span class="keyword">if</span> (graph_state_ &lt; GraphState::Complete) &#123;</span><br><span class="line">    <span class="built_in">LOG</span>(FATAL) &lt;&lt; <span class="string">&quot;Graph need be build!&quot;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">CHECK</span>(graph_state_ == GraphState::Complete)</span><br><span class="line">      &lt;&lt; <span class="string">&quot;Graph status error, current state is &quot;</span> &lt;&lt; <span class="built_in">int</span>(graph_state_);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// input_op为整张图的开始执行节点，也就是模型的执行入口</span></span><br><span class="line">  std::shared_ptr&lt;RuntimeOperator&gt; input_op;</span><br><span class="line">  <span class="keyword">if</span> (input_operators_maps_.<span class="built_in">find</span>(input_name_) == input_operators_maps_.<span class="built_in">end</span>()) &#123;</span><br><span class="line">    <span class="built_in">LOG</span>(FATAL) &lt;&lt; <span class="string">&quot;Can not find the input node: &quot;</span> &lt;&lt; input_name_;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    input_op = input_operators_maps_.<span class="built_in">at</span>(input_name_);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// output_op为整张图的结束执行节点</span></span><br><span class="line">  std::shared_ptr&lt;RuntimeOperator&gt; output_op;</span><br><span class="line">  <span class="keyword">if</span> (output_operators_maps_.<span class="built_in">find</span>(output_name_) ==</span><br><span class="line">      output_operators_maps_.<span class="built_in">end</span>()) &#123;</span><br><span class="line">    <span class="built_in">LOG</span>(FATAL) &lt;&lt; <span class="string">&quot;Can not find the output node: &quot;</span> &lt;&lt; input_name_;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    output_op = output_operators_maps_.<span class="built_in">at</span>(output_name_);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 将输入节点送入到执行队列中</span></span><br><span class="line">  <span class="comment">// operator_queue是一个deque结构，方便从尾部插入，并从头部取出（先进先出）</span></span><br><span class="line">  std::deque&lt;std::shared_ptr&lt;RuntimeOperator&gt;&gt; operator_queue;</span><br><span class="line">  operator_queue.<span class="built_in">push_back</span>(input_op);</span><br><span class="line">  std::map&lt;std::string, <span class="type">double</span>&gt; run_duration_infos;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">while</span> (!operator_queue.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">    <span class="comment">// 从头部取出，出队列</span></span><br><span class="line">    std::shared_ptr&lt;RuntimeOperator&gt; current_op = operator_queue.<span class="built_in">front</span>();</span><br><span class="line">    operator_queue.<span class="built_in">pop_front</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!current_op || current_op == output_op) &#123;</span><br><span class="line">      <span class="built_in">LOG</span>(INFO) &lt;&lt; <span class="string">&quot;Model Inference End&quot;</span>;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (current_op == input_op) &#123;</span><br><span class="line">      <span class="comment">// 如果 当前节点是输入节点，就直接使用ProbeNextLayer将输入拷贝到输入节点的下一层中。</span></span><br><span class="line">      <span class="built_in">ProbeNextLayer</span>(current_op, operator_queue, inputs);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      std::string current_op_name = current_op-&gt;name;</span><br><span class="line">      <span class="comment">// 使用CheckOperatorReady检查当前节点的入度，如果入度等于0，那么当前的节点就允许被执行</span></span><br><span class="line">      <span class="keyword">if</span> (!<span class="built_in">CheckOperatorReady</span>(current_op)) &#123;</span><br><span class="line">        <span class="comment">// 如果这个节点还没有ready，就需要重新被放入到operator_queue当中</span></span><br><span class="line">        <span class="keyword">if</span> (operator_queue.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">          <span class="comment">// 当current op是最后一个节点的时候，说明它已经不能被ready</span></span><br><span class="line">          <span class="built_in">LOG</span>(FATAL) &lt;&lt; <span class="string">&quot;Current operator is not ready!&quot;</span>;</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">// 如果不是最后一个节点，它还有被ready的可能性</span></span><br><span class="line">          operator_queue.<span class="built_in">push_back</span>(current_op);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 从op-&gt;input_operands_seq中拷贝指针到layer_input_datas中</span></span><br><span class="line">      <span class="type">const</span> std::vector&lt;std::shared_ptr&lt;RuntimeOperand&gt;&gt; &amp;input_operand_datas =</span><br><span class="line">          current_op-&gt;input_operands_seq;</span><br><span class="line">      std::vector&lt;std::shared_ptr&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;&gt; layer_input_datas;</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;input_operand_data : input_operand_datas) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;input_data : input_operand_data-&gt;datas) &#123;</span><br><span class="line">          layer_input_datas.<span class="built_in">push_back</span>(input_data);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="built_in">CHECK</span>(!layer_input_datas.<span class="built_in">empty</span>()) &lt;&lt; <span class="string">&quot;Layer input data is empty&quot;</span>;</span><br><span class="line">      <span class="built_in">CHECK</span>(current_op-&gt;output_operands != <span class="literal">nullptr</span> &amp;&amp;</span><br><span class="line">            !current_op-&gt;output_operands-&gt;datas.<span class="built_in">empty</span>())</span><br><span class="line">          &lt;&lt; <span class="string">&quot;Layer output data is empty&quot;</span>;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 执行operator当中的layer计算过程</span></span><br><span class="line">      <span class="comment">// layer的计算结果存放在current_op-&gt;output_operands-&gt;datas中</span></span><br><span class="line">      InferStatus status = current_op-&gt;layer-&gt;<span class="built_in">Forward</span>(</span><br><span class="line">          layer_input_datas, current_op-&gt;output_operands-&gt;datas);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 在执行完毕后，对当前的算子current_op的输出同步它下一级后继节点的输入中</span></span><br><span class="line">      <span class="built_in">ProbeNextLayer</span>(current_op, operator_queue,</span><br><span class="line">                     current_op-&gt;output_operands-&gt;datas);</span><br><span class="line">      <span class="keyword">if</span> (debug) &#123;</span><br><span class="line">        <span class="built_in">LOG</span>(INFO) &lt;&lt; <span class="string">&quot;current operator: &quot;</span> &lt;&lt; current_op-&gt;name;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 如果meet_num的数量等于它前驱的数量，说明它现在可以被放入到执行队列中。</span></span><br><span class="line">  <span class="comment">// 现在所有的算子都执行完毕了，把meet_num置零</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;op : <span class="keyword">this</span>-&gt;operators_) &#123;</span><br><span class="line">    op-&gt;meet_num = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 将output operator的input operand输出为最后的结果，即输出节点的输入张量就是最后得到的结果</span></span><br><span class="line">  <span class="built_in">CHECK</span>(output_op-&gt;input_operands.<span class="built_in">size</span>() == <span class="number">1</span>)</span><br><span class="line">      &lt;&lt; <span class="string">&quot;The graph only support one path to the output node yet!&quot;</span>;</span><br><span class="line">  <span class="type">const</span> <span class="keyword">auto</span> &amp;output_op_input_operand = output_op-&gt;input_operands.<span class="built_in">begin</span>();</span><br><span class="line">  <span class="type">const</span> <span class="keyword">auto</span> &amp;output_operand = output_op_input_operand-&gt;second;  <span class="comment">// 键值对中的value</span></span><br><span class="line">  <span class="keyword">return</span> output_operand-&gt;datas;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2023/03/22/kuiper_infer-L12/">https://kilogrand.gitee.io/2023/03/22/kuiper_infer-L12/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/kuiper-infer/">kuiper_infer</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/21/kuiper_infer-L11/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">自制深度学习框架--再探Tensor类并构建计算图的图关系</div></div></a></div><div class="next-post pull-right"><a href="/2023/03/23/kuiper_infer-L13/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">自制深度学习框架--实现ResNet网络的推理</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-20</div><div class="title">自制深度学习框架--Im2Col原理与卷积层的实现</div></div></a></div><div><a href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-21</div><div class="title">自制深度学习框架--再探Tensor类并构建计算图的图关系</div></div></a></div><div><a href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-24</div><div class="title">自制深度学习框架--实现Yolov5的推理</div></div></a></div><div><a href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-23</div><div class="title">自制深度学习框架--实现ResNet网络的推理</div></div></a></div><div><a href="/2023/03/14/kuiper_infer-L3/" title="自制深度学习框架--导入数据"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-14</div><div class="title">自制深度学习框架--导入数据</div></div></a></div><div><a href="/2023/03/13/kuiper_infer-L2/" title="自制深度学习框架--张量"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-13</div><div class="title">自制深度学习框架--张量</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%A1%E7%AE%97%E5%9B%BE%E6%89%A7%E8%A1%8C%E7%9A%84%E5%9B%BE%E7%A4%BA"><span class="toc-number">1.</span> <span class="toc-text">计算图执行的图示</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%BB%E6%89%BE%E5%B9%B6%E6%8B%B7%E8%B4%9D%E4%B8%8A%E4%B8%80%E7%BA%A7%E7%9A%84%E8%BE%93%E5%87%BA%E5%88%B0%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E7%9A%84%E8%BE%93%E5%85%A5"><span class="toc-number">2.</span> <span class="toc-text">寻找并拷贝上一级的输出到后继节点的输入</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2%E7%9A%84%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.</span> <span class="toc-text">广度优先搜索的执行顺序的实现</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>